package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.zzyl.nursing.domain.dto.CheckInApplyDto;
import com.zzyl.nursing.domain.dto.CheckInContractDto;
import com.zzyl.nursing.domain.po.*;
import com.zzyl.nursing.domain.vo.CheckInApplyVo;
import com.zzyl.nursing.domain.vo.CheckInConfigVo;
import com.zzyl.nursing.domain.vo.CheckInElderVo;
import com.zzyl.nursing.domain.vo.ElderFamilyVo;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.IBedService;
import com.zzyl.nursing.service.ICheckInConfigService;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 入住Service业务层处理
 *
 * @author alexis
 * @date 2025-05-26
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderServiceImpl elderService;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private IBedService bedService;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ICheckInConfigService checkInConfigService;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }


    @Override
    public CheckInApplyVo listById(Integer id) {
//        入住信息
        CheckInConfig checkInConfig = checkInConfigService.getOne(
                new LambdaQueryWrapper<CheckInConfig>()
                        .eq(CheckInConfig::getCheckInId, id));
        CheckIn checkIn = checkInMapper.selectOne(new LambdaQueryWrapper<CheckIn>().eq(CheckIn::getId, id));
//        配置信息
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());


//         家属信息
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> lists = JSON.parseArray(remark, ElderFamilyVo.class);


        Elder elder = elderService.getById(checkIn.getElderId());
//        老人信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
        LocalDate birthDate = LocalDate.parse(
                elder.getBirthday(),
                DateTimeFormatter.ofPattern("yyyy-MM-dd")
        );
        int age = Period.between(birthDate, LocalDate.now()).getYears();
        checkInElderVo.setAge(age);

        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, checkIn.getElderId()));

        CheckInApplyVo checkInApplyVo = new CheckInApplyVo();
        checkInApplyVo.setCheckInConfigVo(checkInConfigVo);
        checkInApplyVo.setElderFamilyVoList(lists);
        checkInApplyVo.setContract(contract);
        checkInApplyVo.setCheckInElderVo(checkInElderVo);

        return checkInApplyVo;
    }

    /**
     * 办理入住
     *
     * @param checkInApplyDto
     * @return
     */
    @Transactional
    @Override
    public int apply(CheckInApplyDto checkInApplyDto) {
        //检查elder表中是否有老人已入住，并且插入数据
        Elder elder = checkElderStatusAndInster(checkInApplyDto);
        // 入住信息插入  分为两个表，入住表checkin 入住信息表 checkinConfig ,两表关联check_in_id与id字段关联
        CheckIn checkIn = insertCheckInData(elder, checkInApplyDto);
        insertCheckInConfig(checkIn, checkInApplyDto);
        //合同表处理
        insertContract(elder, checkInApplyDto);

        return 1;
    }

    private void insertContract(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto, contract);
        contract.setElderId(Integer.parseInt(elder.getId().toString()));

        String contractNumber = "ht" + UUID.randomUUID().toString();
        contract.setContractNumber(contractNumber);
        contract.setElderName(elder.getName());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        Integer status = checkInApplyDto.getCheckInConfigDto().getStartDate().isBefore(LocalDateTime.now()) ? 0 : 1;
        contract.setStatus(status);
        contractMapper.insert(contract);

    }

    private void insertCheckInConfig(CheckIn checkIn, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);

    }

    private CheckIn insertCheckInData(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(Integer.parseInt(elder.getId().toString()));
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStatus(Long.parseLong("0"));
        String jsonRemark = JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList());
        checkIn.setRemark(jsonRemark);

        //插入数据
        checkInMapper.insert(checkIn);

        return checkIn;
    }

    private Elder checkElderStatusAndInster(CheckInApplyDto checkInApplyDto) {
        String idCardNo = checkInApplyDto.getCheckInElderDto().getIdCardNo();

        Elder elder=  elderMapper.selectOne(new LambdaQueryWrapper<Elder>()
                .eq(Elder::getIdCardNo, idCardNo)
                .eq(Elder::getStatus, 1));

        if (ObjectUtils.isNotEmpty(elder)) {
            throw new RuntimeException("用户已经存在，已经入住");
        }
        //插入老人信息
        //更行床位信息，根据bedId
        boolean update = bedService.update(new LambdaUpdateWrapper<Bed>()
                .setSql("bed_status=1")
                .eq(Bed::getId, checkInApplyDto.getCheckInConfigDto().getBedId())
        );
        Bed bed = bedService.getById(checkInApplyDto.getCheckInConfigDto().getBedId());
        //存在信息，重新入住。 新用户
        //表中的数据
        Elder elderOld = elderMapper.selectOne(new LambdaQueryWrapper<Elder>()
                .eq(Elder::getIdCardNo, idCardNo)
                .ne(Elder::getStatus, 1));

        //分装好老人信息
        Elder elderData = new Elder();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInElderDto(), elderData);
        elderData.setStatus(1);
        elderData.setBedNumber(bed.getBedNumber());
        elderData.setBedId(checkInApplyDto.getCheckInConfigDto().getBedId());


        if (ObjectUtils.isNotEmpty(elderOld)) {
            //不为空，跟新
            elderService.updateElder(elderData);
        } else {
            //为空，增加
            elderService.insertElder(elderData);
        }
        return elderData;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }
}
